#! /usr/bin/env python

import socket
import time


def exiter(INPUT : start, exit, portNumber):
  emit("status", "exit")
  print 'Trying to exit networkHelper'
  time.sleep(1)
  host = socket.gethostname()
  sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  sock.connect((host, portNumber))
  sock.send(' '*1024)
  sock.close()


def waitForConnection(INPUTS : list status, serverSocket):
  print 'Status:',str(status)
  if('exit' in status):
    print 'Exiting listen for connections'
    serverSocket.close()
    return
  print 'Listening for a connection'
  serverSocket.listen(5)
  (clientSocket, address) = serverSocket.accept()
  emit("connection", (clientSocket, address))
  emit("status", "continue")
  emit("serverSocket", serverSocket)


def readLength(INPUT : connection):
  print 'Reading message length'
  clientSocket, address = connection
  msg, MSGLEN = '', 1024
  while len(msg) < MSGLEN:
    chunk = clientSocket.recv(MSGLEN-len(msg))
    if chunk == '':
      raise RuntimeError
    msg = msg + chunk
  try:
    emit("length", int(msg))
    emit("connection", connection)
  except ValueError, err:
    print 'Failed to parse message length ->', err


def acceptConnection(INPUT : start, portNumber):
    print 'Opening a socket on port', portNumber
    serverSocket = socket.socket(
        socket.AF_INET, socket.SOCK_STREAM)
    serverSocket.bind((socket.gethostname(), portNumber))
    emit("serverSocket", serverSocket)
    emit("status", "start")


def readMessage(INPUTS : length, connection):
    print 'Reading the message yo'
    print 'length:', length
    clientSocket, address = connection
    msg, MSGLEN = '', length
    while len(msg) < MSGLEN:
        chunk = clientSocket.recv(MSGLEN-len(msg))
        if chunk == '':
            raise RuntimeError
        msg = msg + chunk
    print 'done reading the message'
    emit("message", msg)
